#!/bin/bash
BOOTUP=color
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

if [ `uname -m` = "x86_64" ]; then
        export MARKLIB64="64"
else
        export MARKLIB64=""
fi

echo_success() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "[  "
  [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
  echo -n $"OK"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "  ]"
  echo -ne "\r"
  return 0
}

echo_failure() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "[  "
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo -n $"DOWN"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "  ]"
  echo -ne "\r"
  return 0
}

echo_passed() {
  [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
  echo -n "["
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo -n $"PASSED"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "]"
  echo -ne "\r"
  return 1
}

if [ x$0 = "xbash" ]; then
echo "Error:  Please don't source me - just execute me!";
else
echo $0 | grep ^\? && slashstart="yes"
if [ x$slashstart = "xyes" ]; then
        prefix=`dirname $0`;
else
        ename=`which $0`;
        prefix=`dirname $ename|sed 's:\/\/:\/:g'`;
fi;
prefix=`dirname $prefix`;
prefix=`dirname $prefix`;
export prefix;
source $prefix/etc/xrootd/system.cnf
export LD_LIBRARY_PATH=$prefix/lib$MARKLIB64:$prefix/../globus/lib:$LD_LIBRARY_PATH
USER=${USER:-$LOGNAME}
if [ -z "$USER" ] ; then USER=`id -n -u` ; fi

SCRIPTUSER=$USER

if [ $USER = "root" ]; then
    USER=$XRDUSER
    XRDHOME=`su $XRDUSER  -c "/bin/echo \\\$HOME"`
    if [ $? -eq 0 ]; then
        echo -n ""
    else
        echo Fatal: user '$XRDUSER' does not exist - check your system.conf - abort
        exit
    fi
else 
    XRDHOME=$HOME
fi


if [ "x${XRDBASEDIR}" = "x" ]; then
    XRDBASEDIR=${prefix}
fi

apmonPidFile=$XRDBASEDIR/admin/apmon.pid

checkkeys() {
    installkeys=no
    [ ! -e $XRDHOME/.authz/xrootd/privkey.pem ] && installkeys=yes
    [ ! -e $XRDHOME/.authz/xrootd/pubkey.pem ] && installkeys=yes
    if [ x"$installkeys" = x"yes" ]; then
	mkdir -p $XRDHOME/.authz/xrootd/
	echo "Getting Keys and bootstrapping $XRDHOME/.authz/xrootd/TkAuthz.Authorization ..."
	wget -t 10 alien.cern.ch/keys/pubkey.pem -O $XRDHOME/.authz/xrootd/pubkey.pem
	wget -t 10 alien.cern.ch/keys/privkey.pem -O $XRDHOME/.authz/xrootd/privkey.pem
	chmod 400 $XRDHOME/.authz/xrootd/privkey.pem
	chmod 400 $XRDHOME/.authz/xrootd/pubkey.pem
    fi
    chown -R $XRDUSER $XRDHOME/.authz
    echo "KEY VO:*       PRIVKEY:$XRDHOME/.authz/xrootd/privkey.pem PUBKEY:$XRDHOME/.authz/xrootd/pubkey.pem" > $XRDHOME/.authz/xrootd/TkAuthz.Authorization
    chmod 600 $XRDHOME/.authz/xrootd/TkAuthz.Authorization
    cat $prefix/etc/xrootd/authz.cnf | grep EXPORT >> $XRDHOME/.authz/xrootd/TkAuthz.Authorization
    cat $prefix/etc/xrootd/authz.cnf | grep RULE >> $XRDHOME/.authz/xrootd/TkAuthz.Authorization
}

addcron() {
    rndname="/tmp/cron.$RANDOM.xrd.sh";
    crontab -l | grep -v "xrd.sh" | grep -v "\#" > $rndname;
    cat ${prefix}/etc/xrootd/crontab.xrootd >> $rndname;
    crontab $rndname;
#    crontab -l
    rm -f $rndname;
}

removecron() {
    rndname="/tmp/cron.$RANDOM.xrd.sh";
    crontab -l | grep -v "xrd\.sh" | grep -v "\#|" > $rndname;
    tabcontent=`cat $rndname`;
    if [ x"$tabcontent" = x ]; then
	crontab -r
    else
	crontab $rndname;
	rm -f $rndname;
    fi
}

bootstrap() {
    mkdir -p ${prefix}/etc/xrootd/server/xrootd
    mkdir -p ${prefix}/etc/xrootd/manager/xrootd
    mkdir -p ${prefix}/scripts/xrootd
    mkdir -p ${LOCALROOT}/${LOCALPATHPFX}

    if [ "x$role" = "xserver" ]; then
        chown $XRDUSER ${LOCALROOT}/${LOCALPATHPFX}
    fi

    export osscachetmp=`echo -e $OSSCACHE`;

    cd $prefix
    for name in `find . -type f | grep ".tmp"`; do 
	newname=`echo $name | sed s/\.tmp// `;
	cp  $name $newname;

	# Substitute all the variables into the templates
	perl -pi'*.template' -e 's/OSSCACHE/$ENV{osscachetmp}/g; s/MARKLIB64/$ENV{MARKLIB64}/g; s/LOCALROOT/$ENV{LOCALROOT}/g; s/LOCALPATHPFX/$ENV{LOCALPATHPFX}/g; s/VMSS_SOURCE/$ENV{VMSS_SOURCE}/g; s/XRDUSER/$ENV{XRDUSER}/g; s/METAMGRHOST/$ENV{METAMGRHOST}/g; s/METAMGRPORT/$ENV{METAMGRPORT}/g; s/MANAGERHOST/$ENV{MANAGERHOST}/g; s/XRDSERVERPORT/$ENV{XRDSERVERPORT}/g; s/XRDMANAGERPORT/$ENV{XRDMANAGERPORT}/g;\ s/CMSDSERVERPORT/$ENV{CMSDSERVERPORT}/g; s/CMSDMANAGERPORT/$ENV{CMSDMANAGERPORT}/g; s/PREFIX/$ENV{prefix}/g; s/SERVERONREDIRECTOR/$ENV{SERVERONREDIRECTOR}/g; s/XRDBASEDIR/$ENV{XRDBASEDIR}/g' ${prefix}/$newname;

        # Monalisa stuff which has to be commented out is some cases
	if [ -n "$MONALISA_HOST" ] ; then
	    perl -pi'*.template' -e 's/MONALISA_HOST/$ENV{MONALISA_HOST}/g' $prefix/$newname
	else
	    perl -pi'*.template' -e 's/(.*MONALISA_HOST.*)/#\1/g' $prefix/$newname
	fi

        # XrdAcc stuff which has to be commented out is some cases
        if [ -n "$ACCLIB" ] ; then
            perl -pi'*.template' -e 's/ACCLIB/$ENV{ACCLIB}/g' $prefix/$newname
        else
            perl -pi'*.template' -e 's/(.*ACCLIB.*)/#\1/g; s/(.*ofs\.authorize.*)/#\1/g' $prefix/$newname
        fi

#	if [ -n "$OSSCACHE" ] ; then
#	    echo -e "\n\n\n${OSSCACHE}\n\n\n" >> $prefix/$newname
#	fi

    done;

    if [ ${SYSTEM} = "XROOTD" ]; then unlink ${prefix}/etc/xrootd/server/xrootd.cf >&/dev/null ; ln -s ${prefix}/etc/xrootd/server/xrootd.xrootd.cf ${prefix}/etc/xrootd/server/xrootd.cf; fi;
    if [ ${SYSTEM} = "XROOTD" ]; then unlink ${prefix}/etc/xrootd/manager/xrootd.cf >&/dev/null ;ln -s ${prefix}/etc/xrootd/manager/xrootd.xrootd.cf ${prefix}/etc/xrootd/manager/xrootd.cf; fi;
    if [ ${SYSTEM} = "DPM" ]; then unlink ${prefix}/etc/xrootd/server/xrootd.cf >&/dev/null ; ln -s ${prefix}/etc/xrootd/server/xrootd.dpm.cf ${prefix}/etc/xrootd/server/xrootd.cf; fi;
    if [ ${SYSTEM} = "DPM" ]; then unlink ${prefix}/etc/xrootd/manager/xrootd.cf >&/dev/null ; ln -s ${prefix}/etc/xrootd/manager/xrootd.dpm.cf ${prefix}/etc/xrootd/manager/xrootd.cf; fi;
    rm -f `find ${prefix}/ -name "*.template"`
    if [ ${SYSTEM} = "DPM" ]; then
	if [ -z "$DPM_HOST" ]; then echo -e "\n\n##########################################################################\nWarning: you should define DPM_HOST in the environment of user $USER if you want to run with DPM!!!\n##########################################################################\n";fi
    fi
    cd -;
}

getSrvToMon() {
    srvToMon=""
    if [ -n "$SE_NAME" ] ; then se="${SE_NAME}_" ; fi
    for typ in manager server ; do
        for srv in xrootd cmsd ; do
            pid=`pgrep -f -U $USER "$srv .*$typ" | head -1`
            if [ -n "$pid" ] ; then srvToMon="$srvToMon ${se}${typ}_${srv} $pid" ; fi
        done
    done
}

servMon() {
   if [ -n "$SE_NAME" ] ; then se="${SE_NAME}_" ; fi
   startUp ${prefix}/scripts/ApMon/servMon.sh -p ${apmonPidFile} ${se}xrootd $*
   echo
}

startMon() {
    if [ -z "$MONALISA_HOST" ] ; then return ; fi
    getSrvToMon
    echo -n "Starting ApMon [$srvToMon] ..."
    servMon -f $srvToMon >/dev/null
    echo_passed
    echo
}

killXRD() {
    echo -n "Stopping xrootd/cmsd: "

    pkill -u $USER xrootd
    pkill -u $USER cmsd
    sleep 1
    pkill -9 -u $USER xrootd
    pkill -9 -u $USER cmsd
    pkill -f -u $USER XrdOlbMonPerf

    echo_passed;
    echo

    echo -n "Stopping ApMon:"
    servMon -k
}

execEnvironment() {
    mkdir -p ${XRDBASEDIR}
    mkdir -p ${XRDBASEDIR}/logs/
    mkdir -p ${XRDBASEDIR}/core/${USER}_$1
    mkdir -p ${XRDBASEDIR}/admin/

    cd ${XRDBASEDIR}/core/${USER}_$1
    if [ $USER = "root" ]; then 
	EXECENV="ulimit -n ${XRDMAXFD};ulimit -c unlimited;" 
    else 
	EXECENV="ulimit -c unlimited;"
    fi

    fdmax=`ulimit -n`
    if [ $fdmax -le 65000 ]; then
	echo "Fatal: This machine does not allow more than $fdmax file descriptors. At least 65000 are needed for serious operation - abort"
	exit -1
    fi

    chown -R $XRDUSER ${XRDBASEDIR}/core ${XRDBASEDIR}/logs ${XRDBASEDIR}/admin 
    chmod -R 755 ${XRDBASEDIR}/core ${XRDBASEDIR}/logs ${XRDBASEDIR}/admin 

}

startUp() {
    if [ $SCRIPTUSER = "root" ]; then
	su -s /bin/bash $XRDUSER -c "${EXECENV} $*";
	echo_passed
#	test $? -eq 0 && echo_success || echo_failure
	echo
    else
	ulimit -c unlimited
	$* 
	echo_passed
#	test $? -eq 0 && echo_success || echo_failure
	echo 
    fi
}

handlelogs() {
   cd ${XRDBASEDIR}
   
   if [ ! -d  ./logsbackup ]; then
       mkdir logsbackup
   fi

   todaynow=`date +%Y%m%d`
   if [ ! -f ./logsbackup/logs$todaynow.tar.gz ]; then
       tar cf ./logsbackup/logs$todaynow.tar ./logs
       gzip -f ./logsbackup/logs$todaynow.tar
       find ./logs -type f | grep -v 'xrdlog' | grep -v 'cmslog' | xargs rm
       find ./logs -type f | grep "xrdlog\." | xargs rm
       find ./logs -type f | grep "cmslog\." | xargs rm
       find ./logsbackup -atime +15 | xargs rm
   fi

}

restartXRD() {
    killXRD
    if [ "x$manager" = "xyes" ]; then
	(
	    execEnvironment manager || exit

	    echo -n "Starting xrootd [manager]: "
	    startUp ${prefix}/bin/xrootd -n manager -b $XRDDEBUG -l ${XRDBASEDIR}/logs/xrdlog -c ${prefix}/etc/xrootd/manager/xrootd.cf 
	    echo -n "Starting cmsd   [manager]: "
	    startUp ${prefix}/bin/cmsd -n manager -b $XRDDEBUG -l ${XRDBASEDIR}/logs/cmslog -c ${prefix}/etc/xrootd/manager/xrootd.cf 
	)
    fi
    if [ "x$server" = "xyes" ]; then
	(
	    execEnvironment server || exit

	    echo -n "Starting xrootd [server]: "
	    startUp ${prefix}/bin/xrootd -s -n server -b $XRDDEBUG -l ${XRDBASEDIR}/logs/xrdlog -c ${prefix}/etc/xrootd/server/xrootd.cf 
	    echo -n "Starting cmsd   [server]: "
	    startUp ${prefix}/bin/cmsd -s -n server -b $XRDDEBUG -l ${XRDBASEDIR}/logs/cmslog -c ${prefix}/etc/xrootd/server/xrootd.cf 
	)
    fi
    startMon
}

myhost="$THISHOSTNAME"
if [ "x$myhost" = "x" ]; then
    myhost=`hostname -f`
fi
if [ "x$myhost" = "x" ]; then
    myhost=`hostname`
fi
if [ "x$myhost" = "x" ]; then
    myhost=$HOST
fi

if [ "x$myhost" = "x" ]; then
    echo "Cannot determine hostname. Aborting."
    exit 1
fi

echo "The fully qualified hostname appears to be $myhost"



role="";

if [ "x$myhost" = "x$MANAGERHOST" ]; then
    role="manager";
    if [ "x$SERVERONREDIRECTOR" = "x1" ]; then
	role="all";
    fi
else
    role="server";
fi

if [ "x$role" = "xserver" ]; then
    server="yes"
    nproc=1
else
    server=""
    if [ "x$role" = "xmanager" ]; then
	manager="yes"
	nproc=1
    else
	manager=""
	if [ "x$role" = "xall" ]; then
	    server="yes"
	    manager="yes"
	    nproc=2
	else
	    echo "usage: xrd.sh [-f] [-c] [-k]";
	    echo " [-f] force restart";
	    echo " [-c] check and restart if not running";
	    echo " [-k] kill running processes";
	    exit -1;
	fi
    fi
fi

if [ "x$1" = "x-f" ] ; then
    removecron
    checkkeys
    bootstrap
    addcron
    date
    echo "(Re-)Starting ...."
    restartXRD
fi;

if [ "x$1" = "x-k" ]; then
    removecron
    killXRD
fi

if [ "x$1" = "x-c" ]; then
    removecron
    checkkeys
    bootstrap
    addcron
    nxrd=`pgrep -u $USER xrootd | wc -l | awk '{print $1}'`;
    ncms=`pgrep -u $USER cmsd | wc -l | awk '{print $1}'`;

    if [ $nxrd -lt $nproc -o $ncms -lt $nproc ]; then
	date
	echo "------------------------------------------"
	ps
	echo "------------------------------------------"
	echo "Starting all .... (only $nxrd xrootds $ncms cmsds)"
	restartXRD
	echo "------------------------------------------"
    else
        if [ -n "$MONALISA_HOST" ] ; then
            pid=`cat $apmonPidFile 2>/dev/null`
            lines=`ps -p $pid 2>/dev/null | wc -l`
            if [ $lines -ne 2 ] ; then
                startMon
            fi
        fi
    handlelogs
    exit 0
    fi

    handlelogs
fi

checkstate() {
    echo "******************************************"
    date
    echo "******************************************" 
nxrd=`pgrep -u $USER xrootd | wc -l | awk '{print $1}'`;
ncms=`pgrep -u $USER cmsd | wc -l | awk '{print $1}'`;

returnval=0    
if [ $nxrd -eq $nproc ]; then
    echo -n "xrootd:";
    echo_success;
    echo
else
    echo -n "xrootd:";
    echo_failure;
    echo
    returnval=1;
fi

if [ $ncms -eq $nproc ]; then
    echo -n "cmsd :";
    echo_success;
    echo
else
    echo -n "cmsd :";
    echo_failure;
    echo
    returnval=1;
fi

if [ -n "$MONALISA_HOST" ] ; then
    pid=`cat $apmonPidFile 2>/dev/null`
    lines=`ps -p $pid 2>/dev/null | wc -l`
    if [ $lines -eq 2 ] ; then
       echo -n "apmon:";
       echo_success;
       echo
    else
       echo -n "apmon:";
       echo_failure;
       echo
       returnval=1;
    fi
fi

exit $returnval
}
fi

sleep 1
checkstate

